import React, { useContext, useRef, useState } from 'react';
import { BaseHelp, BaseHelpProps, HelpContext, Table } from '../../functionalComponent';
import { borderStyle, compHoc, getGlobalConfig, IObject, Layout, iup, useApi, useRefCallback } from '../../util';
import { getHelpBeforeOpen } from './common';
const { Flex, Slider } = Layout;

const { Header, Footer, MultipleButtons } = BaseHelp;

const tableProps: any = {
  rowSelected: false,
  rowChecked: true,
  cache: false,
  headerMenu: false,
  style: { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 }
};

function HelpContent() {
  const {
    request,
    ok,
    contentParams: { getFieldValue, columns, helpTitle, helpId, selectedArray, multiple, footer },
    randomKey
  } = useContext<any>(HelpContext);
  const btnRef = useRef<any>();
  const formRef = useApi();
  const [activeKey, setActiveKey] = useState('0');
  const rightTable = useRef<any>();
  const getTable = () => iup.compIns[`${helpId}_${randomKey}_${activeKey}`].getApi();
  const getResult: any = () => {
    if (multiple) {
      const result = rightTable.current
        .getApi()
        .getRows()
        .map((r: any) => ({
          value: getFieldValue(r),
          label: getFieldValue(r, 'label'),
          origin: { ...r }
        }));
      return result.length > 0 ? result : undefined;
    } else {
      const value = getTable().getSelectedData()[0];
      if (value) {
        return { value: getFieldValue(value), label: getFieldValue(value, 'label'), origin: { ...value } };
      }
      return undefined;
    }
  };
  const toRight = (values: any) => {
    if (multiple) {
      btnRef.current.toRight(values);
    } else {
      ok(getResult());
    }
  };

  tableProps.checkbox = multiple ? 'checked' : false;
  tableProps.rowSelected = !multiple;
  tableProps.rowChecked = multiple;

  const renderTable = (index: number) => {
    return (
      <Table
        {...tableProps}
        style={{ ...tableProps.style }}
        id={`${helpId}_${randomKey}_${index}`}
        columns={columns}
        onRow={(rowIndex: any, table: { getRow: (arg0: any) => any }) => ({
          onDoubleClick: () => toRight([table.getRow(rowIndex)])
        })}
        // autoLoad={false}
        request={request}
        // pagination={{
        //   height: 32,
        //   showQuickJumper: false,
        //   align: 'left',
        //   targetContainer: multiple && index === 0 ? `${helpId}_${randomKey}_pagination` : ''
        // }}
        // response={(res: { total: any; list: any }) => ({ total: res.total ?? 0, record: res.list || [] })}
      />
    );
  };

  return (
    <Layout>
      <Header title={helpTitle || '预警方案帮助'} />
      <Flex direction="row" style={{ padding: '16px 16px 0 16px' }}>
        <Layout.Flex style={{ paddingBottom: multiple ? 32 : 0 }}>{renderTable(0)}</Layout.Flex>
        {multiple && (
          <MultipleButtons
            getRowKey={getFieldValue}
            outRef={btnRef}
            getActiveTable={getTable}
            getResultTable={() => rightTable.current.getApi()}
          />
        )}
        {multiple && (
          <Layout.Flex style={{ paddingTop: 7, paddingBottom: activeKey === '0' ? 32 : 0 }}>
            <Table
              {...tableProps}
              columns={columns}
              dataSource={selectedArray}
              ref={rightTable}
              onRow={(rowIndex: any) => ({
                onDoubleClick: () => btnRef.current.toLeft(rowIndex)
              })}
            />
            <div
              id={`${helpId}_${randomKey}_pagination`}
              style={{
                position: 'absolute',
                left: 221,
                right: 5,
                ...borderStyle(['left', 'right', 'bottom']),
                paddingLeft: 10
              }}
            />
          </Layout.Flex>
        )}
      </Flex>
      <Footer getResult={getResult}>{footer && <span style={{ flex: 1, width: 0 }} children={footer} />}</Footer>
    </Layout>
  );
}

interface IParam {
  pageNum?: number;
  pageSize?: number;
  pluginCode: string; // 插件编码
  indicatorsData: string; // 指标值
  indicatorsCode: string; // 参数编码
  orgCode: string; // 组织编码
  [prop: string]: any; // 额外参数
  clientSqlFilter?:
    | string
    | IObject
    | (({
        ds,
        row,
        value,
        dataIndex,
        helpId
      }: {
        ds: Array<any>;
        row: any;
        value: any;
        dataIndex: string;
        helpId: string;
      }) => string | IObject); // 查询参数
}

export interface BaseDedicatedHelp {
  /**
   * @description        同labelField,优先级略低
   */
  displayField?: string;
  /**
   * @description       自定义弹出帮助的title
   */
  title?: string;
  /**
   * @description       是否开启多选模式
   * @default           false
   */
  multiple?: boolean;
  /**
   * @description       底部扩展组件
   */
  footer?: React.ReactNode;
  /**
   * @description       表格列配置
   */
  columns?: IObject[];
  /**
   * @description       接口列表参数
   * {
        pluginCode: string; // 插件编码
        indicatorsData: string; // 指标值
        indicatorsCode: string; // 参数编码
        orgCode: string; // 组织编码;
      };
   */
  params?: IParam;
  /**
   * @description       自定义请求
   */
  customRequest?: (params: IParam | undefined) => Promise<{ list: any[]; total: number | string }>;
  /**
   * @description   查询参数
   */
  clientSqlFilter?:
    | string
    | IObject
    | (({
        ds,
        row,
        value,
        dataIndex
      }: {
        ds: Array<any>;
        row: any;
        value: any;
        dataIndex: string;
        helpId: string;
      }) => string | IObject);
}

export type IDedicatedHelp = BaseDedicatedHelp & BaseHelpProps;

/**
 * 指标帮助
 */
export const DedicatedHelp = compHoc<IDedicatedHelp>((props) => {
  const cacheHelpInfo = useRef({ data: null, p: null });
  const {
    valueField = 'schemeCode',
    labelField = 'schemeName',
    displayField,
    userCodeField,
    clientSqlFilter,
    title,
    multiple = false,
    modalProps,
    footer,
    customRequest,
    params = {},
    columns,
    onBeforeOpen,
    ...others
  } = props;
  const otherProps: any = others;

  otherProps.onBeforeOpen = useRefCallback(async () => {
    const [status, helpInfo] = await getHelpBeforeOpen({ onBeforeOpen, cacheHelpInfo });
    if (iup.isObject(helpInfo)) {
      return helpInfo;
    }
    return status;
  });

  otherProps.request = useRefCallback(async ({ pageIndex, pageSize }: any) => {
    if (customRequest) {
      return await customRequest(params as IParam);
    }
    return iup.request
      .body({
        url: '/iup-early-warning/warnSchemeDefine/listByIndicators',
        data: params
      })
      .then((res) => {
        if (res?.code === 0) {
          return res?.data;
        } else {
          return { list: [], total: 0 };
        }
      });
  });
  otherProps.valueField = valueField;
  otherProps.userCodeField = userCodeField;
  otherProps.labelField = labelField || displayField;
  // 自定义modal弹出窗需要使用的参数
  otherProps.contentParams = {
    footer,
    multiple,
    valueField,
    labelField: otherProps.labelField,
    columns: columns ?? [
      { dataIndex: 'schemeCode', title: '预警编码' },
      { dataIndex: 'schemeName', title: '预警名称', tooltip: true },
      {
        dataIndex: 'sharePolicy',
        title: '共享策略',
        render: ({ row }) => {
          const { sharePolicy } = row;
          const policyMaps = {
            0: '集团共享',
            1: '单元共享',
            2: '组织私有'
          };
          return policyMaps[sharePolicy];
        }
      },
      { dataIndex: 'tenantName', title: '所属单元', tooltip: true },
      { dataIndex: 'insertOrgName', title: '所属组织', tooltip: true }
    ]
  };
  if (title) {
    otherProps.contentParams.helpTitle = title;
  }
  const { width, height } = getGlobalConfig().default.helpConfig;
  return (
    <BaseHelp
      {...otherProps}
      modal
      helpContent={HelpContent}
      multiple={multiple}
      modalProps={{ width, height, ...modalProps }}
    />
  );
}, 'DedicatedHelp');

export default DedicatedHelp;
